#!/usr/bin/python
from django.shortcuts import HttpResponse, redirect
from chtozadali.core.models.user import User
from chtozadali.core.models.task import UserTask
from django.contrib.auth.decorators import login_required
from chtozadali.core.views.utilits import check_for_params

def prepare_response(d):
    if d:
        return str(d).replace("'", '"')
    else:
        return str("{}")
    return d

def get_main(request):
    return HttpResponse(prepare_response({}))

def get_user_exists(request):
    if request.method == "GET":
        try:
            User.objects.get(username=request.GET["uname"])
        except:
            return HttpResponse(prepare_response({"exists": "false"}))
        return HttpResponse(prepare_response({"exists": "true"}))

@login_required
def change_task_done(request):
    if request.method == "POST":
        tid = request.POST.get("tid", False)
        tid_state = request.POST.get("tids", False)
        if tid and tid_state:
            try:
                obj = UserTask.objects.get(task__id=int(tid))
            except:
                return HttpResponse(prepare_response({"success": "false", "reason": "no_such_usertask_object"}))
            else:
                if tid_state == "true":
                    obj.is_done = True
                else:
                    obj.is_done = False
                obj.save()
                return HttpResponse(prepare_response({"success": "true"}))
        else:
            return HttpResponse(prepare_response({"success": "false", "reason": "too_few_parameters"}))
